package com.zmc.order.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmc.order.infrastructure.entity.CommentInfoEntity;
import com.zmc.order.infrastructure.enums.CommentEnum;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmc.order.infrastructure.dao.CommentAggregateDao;
import com.zmc.order.infrastructure.entity.CommentAggregateEntity;
import com.zmc.order.infrastructure.service.CommentAggregateService;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author zmc
 */
@Service("commentAggregateService")
public class CommentAggregateServiceImpl extends ServiceImpl<CommentAggregateDao, CommentAggregateEntity> implements CommentAggregateService {

    @Override
    public CommentAggregateEntity getBySpuId(String spuId) {
        LambdaQueryWrapper<CommentAggregateEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommentAggregateEntity::getSpuId, spuId).last("limit 1");
        return getOne(wrapper);
    }

    @Override
    @Transactional
    public void commentAggregate(CommentInfoEntity info, boolean flag) {
        CommentAggregateEntity aggregate = getBySpuId(info.getSpuId());
        if (aggregate == null) {
            aggregate = new CommentAggregateEntity();
            aggregate.setSpuId(info.getSpuId());
            aggregate.setTotalCommentCount(0L);
            aggregate.setGoodCommentCount(0L);
            aggregate.setGoodCommentRate(BigDecimal.ZERO);
            aggregate.setShowPicturesCommentCount(0L);
            aggregate.setMediumCommentCount(0L);
            aggregate.setBadCommentCount(0L);
        }
        int count = flag ? 1 : -1;
        Integer totalScore = info.getTotalScore();
        aggregate.setTotalCommentCount(aggregate.getTotalCommentCount() + count);
        if (CommentEnum.IS_SHOW_PICTURE.getStatus() == info.getIsShowPictures()) {
            aggregate.setShowPicturesCommentCount(aggregate.getShowPicturesCommentCount() + count);
        }
        if (totalScore == 3) {
            //中评
            aggregate.setMediumCommentCount(aggregate.getMediumCommentCount() + count);
        } else if (totalScore < 3) {
            //差评
            aggregate.setBadCommentCount(aggregate.getBadCommentCount() + count);
        } else {
            //好评
            aggregate.setGoodCommentCount(aggregate.getGoodCommentCount() + count);
            aggregate.setGoodCommentRate(BigDecimal.valueOf(aggregate.getGoodCommentCount()).divide(BigDecimal.valueOf(aggregate.getTotalCommentCount()), 2, RoundingMode.HALF_UP));
        }
        saveOrUpdate(aggregate);
    }

}